#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
from cli.base import CveTrackingCommand
from conf import CONFIG
from core.comment.issue_comment import issue_comment
from core.crawler.patch import Patch
from exception import InputError
from logger import logger
from util.gitee_api import Gitee


class CommentCommand(CveTrackingCommand):
    """
    Comment function command line
    """

    def __init__(self):
        super(CommentCommand, self).__init__()
        self.parser = CveTrackingCommand.sub_parse.add_parser(
            "comment", help="Add a comment to the issue on gitee"
        )
        self._add_common_param()
        self.parser.add_argument(
            "-i",
            "--issue",
            metavar="issue",
            type=str,
            required=True,
            action="store",
            default=None,
            help="CVE related issue number",
        )

    @staticmethod
    async def run_command(args):
        """
        Comment function execution entrance
        :param args: command line params
        :return: None
        """
        logger.info("Start to perform search and comment functions")
        if not all([args.cve_num, args.rpm_name, args.issue]):
            raise InputError(msg="Comment command parameters: cve_num/rpm_name/issue")

        # find patch detail
        patch_obj = Patch(cve_num=args.cve_num, rpm_name=args.rpm_name)
        patch_details = await patch_obj.find_patches_detail()

        # comment cve issue
        gitee = Gitee()
        gitee.set_attr(owner=CONFIG.DEFAULT_OWNER, repo=args.rpm_name)
        await issue_comment(patch_details=patch_details, number=args.issue, gitee=gitee)
        logger.info("End to perform search and comment functions")
